from app.api.deps import SessionDep
from app.crud import create_project, create_project, get_project_by_name
from app.models import Project, ProjectPublic, ProjectsResponse
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select

router = APIRouter(prefix="/project", tags=["projects"])

@router.get("/",response_model=ProjectsResponse)
async def get_projects(session:SessionDep,skip: int = 0, limit: int = 100):
    statement = select(Project).offset(skip).limit(limit)
    results = session.exec(statement)
    data = [ProjectPublic(id=project.id, name=project.name) for project in results]
    count_statement = (
            select(func.count())
            .select_from(Project)

        )
    count = session.exec(count_statement).one()
    return ProjectsResponse(
        data=data,
        count=count if count else 0
    )

@router.post("/")
async def create_project_api(project: ProjectPublic, session: SessionDep):
    project_ = get_project_by_name( session,project.name)
    if project_:
        raise HTTPException(
            status_code=400,
            detail=f"项目 '{project.name}' 已经存在."
        )
    create_project(session=session, name=project.name)

@router.delete("/{project_id}")
async def delete_project_api(project_id: str, session: SessionDep):
    project = session.get(Project, project_id)
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    session.delete(project)
    session.commit()